package com.zhang.flink.example;

import com.zhang.flink.example.source.IntegerSource;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @title: reduce同时求最大值和最小值
 * @author: zhang
 * @date: 2022/2/11 19:43
 */
public class ReduceMaxAndMin {
    public static void main(String[] args) throws Exception {
        // todo 获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .map(r -> Tuple2.of(r, r))
                // 泛型擦出这里做处理
                .returns(Types.TUPLE(Types.INT, Types.INT))
                // 因为要求最大值和最小值，所以应该对全局进行处理，这里keyBy到同一个逻辑分区
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(
                                value1.f0 > value2.f0 ? value1.f0 : value2.f0,
                                value1.f1 > value2.f1 ? value2.f1 : value1.f1
                        );
                    }
                })
                .print();

        env.execute();
    }
}
